package com.unitreport.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import com.unitreport.domain.UnitCmd;

public class ExecuteCmdImpl implements ExecuteCmdI {

	public void excute(List<UnitCmd> cmdList) {
		for(UnitCmd unitCmd : cmdList) {
			System.out.println("----------------> " +unitCmd.getCmd());
			doExcute(unitCmd);
		}
		
	}
	
	private void doExcute(UnitCmd unitCmd) {
		try {

            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(unitCmd.getCmd());
           
            // any error message?
           /* StreamGobbler errorGobbler = new
                StreamGobbler(unitCmd, proc.getErrorStream(), "ERROR");*/

            // any output?
            StreamGobbler outputGobbler = new
                StreamGobbler(unitCmd, proc.getInputStream(), "OUTPUT");

            // kick them off
           // errorGobbler.start();
            outputGobbler.start();

            // any error???
            int exitVal = proc.waitFor();
            //System.out.println("ExitValue: " + exitVal);
            
        } catch (Throwable t) {
            t.printStackTrace();
        }
		
	}

}

class StreamGobbler extends Thread {
    private InputStream is;
    private String type;
    private UnitCmd unitCmd;

    StreamGobbler(UnitCmd unitCmd, InputStream is, String type) {
        this.is = is;
        this.type = type;
        this.unitCmd = unitCmd;
    }

    public void run() {
    	ValidaterI validater = new ValidaterImpl();
    	//System.out.println("【"+this.type+"】---------------------->");
        try  {
            InputStreamReader isr = new InputStreamReader(is,"gbk");
            BufferedReader br = new BufferedReader(isr);
            StringBuffer sb = new StringBuffer();
            String line=null;
            
            while ( (line = br.readLine()) != null) {
//            	System.out.println(line);
            	sb.append(line + "\n");
            }
            
            unitCmd.setExecuteInfo(sb.toString());
            
           //System.out.println(sb.toString());
            validater.validate(unitCmd);
            
        } catch (IOException e) {
        	throw new RuntimeException(e);
        }
    }
}

